package com.cms.manage.aspect;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import com.cms.manage.util.RequestMapToUtil;

@Aspect  
@Component 
public class LDataNullVerifyAspect {

	private static Logger logger = Logger.getLogger(LDataNullVerifyAspect.class);

	@Around("within(com.cms.manage.controller.*.*) && @annotation(ldataNullVerify)")
	public Object DataVerify(ProceedingJoinPoint joinPoint, LDataNullVerify ldataNullVerify) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", null);
		try {
			Object[] args = joinPoint.getArgs();
			HttpServletRequest request = null;
			for (int i = 0; i < args.length; i++) {
				if (args[i] instanceof HttpServletRequest) {
					request = (HttpServletRequest) args[i];
					break;
				}
			}
			if (request == null) {
				map.put("status", "0");
				map.put("message", "方法中缺失HttpServletRequest参数！");
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(map);
			}
			Map<String,String> data =RequestMapToUtil.getPostByTextPlain(request);
			try {
				String ip = request.getRemoteAddr(); 
				String url = request.getRequestURL().toString();		
				List<String> dataKeys = Arrays.asList(ldataNullVerify.value().split(","));				
				if(dataKeys.size()>0){
					for (int i = 0; i < dataKeys.size(); i++) {
						if(data.get(dataKeys.get(i))==null||"".equals(data.get(dataKeys.get(i)))){
							map.put("status", "0");
							map.put("message", "请求中缺失"+dataKeys.get(i)+"参数！");
							logger.info("用户IP[" + ip + "]访问地址[" + url + "]缺失参数[" + dataKeys.get(i) + "]");  
							return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(map);	
						}			
					}
				}
				return joinPoint.proceed();
			} catch (Exception e) {
				map.put("status", "0");
				map.put("message", "系统异常" + e.getMessage());
				return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
			}
		} catch (Throwable e) {
			map.put("status", "0");
			map.put("message", "系统异常");
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
		}
	}

}
